package com.magictower.primary.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.magictower.primary.R;

import java.util.ArrayList;
import java.util.HashMap;

public class ContactActivity extends AppCompatActivity {

    //contacts表
    //联系人表的URI —— content://com.android.contacts/contact ，对应类静态常量为ContactsContract.Contacts.CONTENT_URI
    //联系人电话URI —— content://com.android.contacts/data/phones ，对应静态常量为ContactsContract.CommonDataKinds.Phone.CONTENT_URI
    //联系人邮箱URI —— content://com.android.contacts/data/emails  ，对应静态常量为ContactsContract.CommonDataKinds.Email.CONTENT_URI
    //联系人地址URI —— content://com.android.contacts/data/postals  ，对应静态常量为ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI
    //所有联系人的Uri —— content://contacts/people
    //某个联系人x的Ur —— content://contacts/people/x

    //Uri rawContactsUri = Uri.parse("content://com.android.contacts/raw_contacts");
    Uri rawContactsUri = ContactsContract.RawContacts.CONTENT_URI;
    Uri phoneLookupUri = Uri.parse("content://com.android.contacts/data/phones");

    private ArrayList<HashMap<String, String>> contactsList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact);

        ListView lvContacts = (ListView) findViewById(R.id.lv_contacts);
        contactsList = readContacts();
        lvContacts.setAdapter(new SimpleAdapter(this, contactsList, R.layout.item_contact_list,
                new String[]{"name", "phone"}, new int[]{R.id.tv_name, R.id.tv_phone}));

        lvContacts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String phone = contactsList.get(position).get("phone");// 读取当前item的电话号码
                Intent intent = new Intent();
                intent.putExtra("phone", phone);
                setResult(Activity.RESULT_OK, intent);// 将数据放在intent中返回给上一个页面

                finish();
            }
        });


    }

    private void testData(String contactId) {
        Cursor phoneLookupCursor = getContentResolver().query(phoneLookupUri,
                null, "contact_id = ?", new String[]{contactId}, null);
        //查找表标题方式

        if (phoneLookupCursor != null) {
            int length = phoneLookupCursor.getColumnCount();
            while (phoneLookupCursor.moveToNext()) {
                for (int i = 0; i < length; i++) {
                    System.out.println(phoneLookupCursor.getColumnName(i) + " : " + phoneLookupCursor.getString(i));
                }
            }
            phoneLookupCursor.close();//关闭
        }
    }

    private ArrayList<HashMap<String, String>> readContacts() {
        // 首先,从raw_contacts中读取联系人的id("contact_id")
        // 其次, 根据contact_id从data表中查询出相应的电话号码和联系人名称
        // 然后,根据mimetype来区分哪个是联系人,哪个是电话号码

        ArrayList<HashMap<String, String>> list = new ArrayList<>();
        HashMap<String, String> map = new HashMap<>();

        Cursor rawContactsCursor = getContentResolver().query(rawContactsUri,
                new String[]{"contact_id", "display_name"}, null, null, null);
        if (rawContactsCursor != null) {
            String displayName;
            String contactId;
            String phone;
            Cursor phoneLookupCursor;
            while (rawContactsCursor.moveToNext()) {
                contactId = rawContactsCursor.getString(0);
                displayName = rawContactsCursor.getString(1);
                System.out.println(contactId + ":" + displayName);

                phoneLookupCursor = getContentResolver().query(phoneLookupUri,
                        new String[]{"data1"}, "contact_id = ?", new String[]{contactId}, null);

                if (phoneLookupCursor != null) {
                    while (phoneLookupCursor.moveToNext()) {
                        phone = phoneLookupCursor.getString(0);
                        map.put("name", displayName);
                        map.put("phone", phone);
                        list.add(map);
                        map = new HashMap<>();
                    }
                    phoneLookupCursor.close();//关闭
                }
            }
            rawContactsCursor.close();//关闭
        }
        return list;

    }
}
